package czk.concrent.juc.cyclicbarrier.practice;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * cyclicBarrier的应用
 *
 * @Author:ChenZhangKun
 * @Date: 2020/12/30 21:42
 */
public class CyclicBarrierApplication {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger sum1 = new AtomicInteger(0);
        AtomicInteger sum2 = new AtomicInteger(0);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            System.out.println(getSum(sum1.get(), sum2.get()));
        });
        new Thread(() -> {

            for (int i = 0; i < 5; i++) {
                sum1.addAndGet(i);
            }
            try {
                // 该线程任务做完后再通知自己已经到达
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {

            for (int i = 0; i < 5; i++) {
                sum2.addAndGet(i);
            }
            try {
                // 该线程任务做完后再通知自己已经到达
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public static int getSum(int sum1, int sum2) {
        return sum1 + sum2;
    }
}
